package com.boruan.shengtangfeng.core.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boruan.shengtangfeng.core.dao.IApplyForDao;
import com.boruan.shengtangfeng.core.dao.IGroupChatDao;
import com.boruan.shengtangfeng.core.dao.IUserDao;
import com.boruan.shengtangfeng.core.entity.ApplyFor;
import com.boruan.shengtangfeng.core.entity.GroupChat;
import com.boruan.shengtangfeng.core.entity.GroupMembers;
import com.boruan.shengtangfeng.core.entity.User;
import com.boruan.shengtangfeng.core.tencentEntity.*;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ims.v20201229.ImsClient;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationRequest;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationResponse;
import com.tencentcloudapi.vm.v20201229.VmClient;
import com.tencentcloudapi.vm.v20201229.models.CreateVideoModerationTaskRequest;
import com.tencentcloudapi.vm.v20201229.models.CreateVideoModerationTaskResponse;
import com.tencentcloudapi.vm.v20201229.models.StorageInfo;
import com.tencentcloudapi.vm.v20201229.models.TaskInput;
import com.tencentyun.TLSSigAPIv2;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.util.*;
import java.util.zip.Deflater;


@Component
public class TencentUtil {

    @Value("${tencent.secretid}")
    private String secretId;
    @Value("${tencent.secretkey}")
    private String secretKey;
    @Value("${tencent.administrator}")
    private String adminIstrator;
    private String region = "ap-shanghai";
    @Autowired
    private IUserDao userDao;
    @Autowired
    private IApplyForDao applyForDao;
    @Autowired
    private IGroupChatDao groupChatDao;

    /**
     * 鉴别图片内容
     *
     * @param imgUrl
     * @return Block：建议屏蔽，Review：建议复审，Pass：建议通过
     */
    public String ims(String imgUrl) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            Credential credential = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            //  从3.1.16版本开始, 单独设置 HTTP 代理
            // httpProfile.setProxyHost("真实代理ip");
            // httpProfile.setProxyPort(真实代理端口);
            httpProfile.setReqMethod("GET"); // get请求(默认为post请求)
            httpProfile.setProtocol("https://");  // 在外网互通的网络环境下支持http协议(默认是https协议),请选择(https:// or http://)
            httpProfile.setConnTimeout(30); // 请求连接超时时间，单位为秒(默认60秒)
            httpProfile.setWriteTimeout(30);  // 设置写入超时时间，单位为秒(默认0秒)
            httpProfile.setReadTimeout(30);  // 设置读取超时时间，单位为秒(默认0秒)
            httpProfile.setEndpoint("ims.tencentcloudapi.com"); // 指定接入地域域名(默认就近接入)

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("TC3-HMAC-SHA256"); // 指定签名算法(默认为HmacSHA256)
            clientProfile.setHttpProfile(httpProfile);
            clientProfile.setDebug(true);

            ImsClient imsClient = new ImsClient(credential, region, clientProfile);

            ImageModerationRequest req = new ImageModerationRequest();
            req.setFileUrl(imgUrl);
            ImageModerationResponse resp = imsClient.ImageModeration(req);

            return resp.getSuggestion();
        } catch (TencentCloudSDKException e) {
            return e.toString();
        }
    }

    /**
     * 创建视频内容审核任务
     *
     * @param videoUrl
     * @return
     */
    public String createVMTask(String videoUrl) {
        try {
            //实例化认证对象
            Credential credential = new Credential(secretId, secretKey);
            //实例化请求对象
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("vm.tencentcloudapi.com");
            //实例化一个用户端
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            VmClient client = new VmClient(credential, "", clientProfile);
            CreateVideoModerationTaskRequest req = new CreateVideoModerationTaskRequest();
            //设置回调地址
            req.setCallbackUrl("https://www.baidu.com");
            //处理请求数据格式
            TaskInput[] taskInputs1 = new TaskInput[1];
            TaskInput taskInput1 = new TaskInput();
            taskInput1.setDataId("1");
            StorageInfo storageInfo1 = new StorageInfo();
            storageInfo1.setType("URL");
            storageInfo1.setUrl(videoUrl);
            taskInput1.setInput(storageInfo1);

            taskInputs1[0] = taskInput1;

            req.setTasks(taskInputs1);
            CreateVideoModerationTaskResponse resp = client.CreateVideoModerationTask(req);

            return CreateVideoModerationTaskResponse.toJsonString(resp);
        } catch (TencentCloudSDKException e) {
            return e.toString();
        }
    }


    /**
     * 获取请求的Url
     *
     * @param servicename
     * @return
     */
    public String getUrl(String servicename) {
        String url = "https://console.tim.qq.com/v4/" + servicename + "?" + "usersig=" + this.GetSign(adminIstrator) + "&identifier=" + adminIstrator + "&sdkappid=" + secretId +
                "&random=" + randomInt() + "&contenttype=json";
        return url;
    }

    /**
     * 获取签名
     *
     * @param uid
     * @return
     */
    public String GetSign(String uid) {
        GenTLSSignatureResult result = null;
        try {
            long expire = (long) 60 * 60 * 24 * 7;
            TLSSigAPIv2 api = new TLSSigAPIv2(Long.valueOf(secretId), secretKey);
            String userSig = api.genSig(uid, expire);
            return userSig;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.urlSig;
    }

    /**
     * @param skdAppid   应用的 sdkappid
     * @param identifier 用户 id
     * @param privStr    私钥文件内容
     * @return
     * @throws IOException
     * @brief 生成 tls 票据，精简参数列表，有效期默认为 180 天
     */
    private GenTLSSignatureResult GenTLSSignatureEx(long skdAppid, String identifier, String privStr) throws IOException {
        return GenTLSSignatureEx(skdAppid, identifier, privStr, 3600 * 24 * 180);
    }

    /**
     * @param skdAppid   应用的 sdkappid
     * @param identifier 用户 id
     * @param privStr    私钥文件内容
     * @param expire     有效期，以秒为单位，推荐时长一个月
     * @return
     * @throws IOException
     * @brief 生成 tls 票据，精简参数列表
     */
    private GenTLSSignatureResult GenTLSSignatureEx(
            long skdAppid,
            String identifier,
            String privStr,
            long expire) throws IOException {

        GenTLSSignatureResult result = new GenTLSSignatureResult();

        Security.addProvider(new BouncyCastleProvider());
        Reader reader = new CharArrayReader(privStr.toCharArray());
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        PEMParser parser = new PEMParser(reader);
        Object obj = parser.readObject();
        parser.close();
        PrivateKey privKeyStruct = converter.getPrivateKey((PrivateKeyInfo) obj);

        String jsonString = "{"
                + "\"TLS.account_type\":\"" + 0 + "\","
                + "\"TLS.identifier\":\"" + identifier + "\","
                + "\"TLS.appid_at_3rd\":\"" + 0 + "\","
                + "\"TLS.sdk_appid\":\"" + skdAppid + "\","
                + "\"TLS.expire_after\":\"" + expire + "\","
                + "\"TLS.version\": \"201512300000\""
                + "}";

        String time = String.valueOf(System.currentTimeMillis() / 1000);
        String SerialString =
                "TLS.appid_at_3rd:" + 0 + "\n" +
                        "TLS.account_type:" + 0 + "\n" +
                        "TLS.identifier:" + identifier + "\n" +
                        "TLS.sdk_appid:" + skdAppid + "\n" +
                        "TLS.time:" + time + "\n" +
                        "TLS.expire_after:" + expire + "\n";

        try {
            //Create Signature by SerialString
            Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
            signature.initSign(privKeyStruct);
            signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
            byte[] signatureBytes = signature.sign();

            String sigTLS = Base64.encodeBase64String(signatureBytes);

            //Add TlsSig to jsonString
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            jsonObject.put("TLS.sig", (Object) sigTLS);
            jsonObject.put("TLS.time", (Object) time);
            jsonString = jsonObject.toString();

            //compression
            Deflater compresser = new Deflater();
            compresser.setInput(jsonString.getBytes(Charset.forName("UTF-8")));

            compresser.finish();
            byte[] compressBytes = new byte[512];
            int compressBytesLength = compresser.deflate(compressBytes);
            compresser.end();
            String userSig = new String(base64_url.base64EncodeUrl(Arrays.copyOfRange(compressBytes, 0, compressBytesLength)));

            result.urlSig = userSig;
        } catch (Exception e) {
            e.printStackTrace();
            result.errMessage = "generate usersig failed";
        }

        return result;
    }

    /**
     * @param url
     * @param
     * @return
     * @see
     */
    public String executePost(String url, String parameters) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost method = new HttpPost(url);
        String body = null;
        if (method != null & parameters != null && !"".equals(parameters.trim())) {
            try {
                //建立一个NameValuePair数组，用于存储欲传送的参数
                method.addHeader("Content-type", "application/json; charset=utf-8");
                method.setHeader("Accept", "application/json");
                method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
                HttpResponse response = closeableHttpClient.execute(method);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    System.out.println(response.getStatusLine());
                    return null;
                }
                //获取响应数据
                body = EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return body;
    }

    /**
     * 生成随机数
     *
     * @see
     */
    public int randomInt() {
        String nineRandom = UUIDUtil.nineRandom();
        return Integer.valueOf(nineRandom);
    }

    /**
     * 添加好友
     *
     * @param applyFor
     * @return
     */
    public Boolean friendAdd(ApplyFor applyFor) {
        Boolean flag = false;
        FriendAddParam friendAddParam = new FriendAddParam();
        friendAddParam.setFrom_Account(applyFor.getApplyId().toString());
        FriendAddParamList paramList = new FriendAddParamList();
        paramList.setTo_Account(applyFor.getRelevanceId().toString());
        if (applyFor.getApplyRemark() != null && !applyFor.getApplyRemark().equals("")) {
            paramList.setAddWording(applyFor.getApplyRemark());
        }
        paramList.setAddSource("AddSource_Type_STF");
        ArrayList<FriendAddParamList> lists = new ArrayList<>();
        lists.add(paramList);
        friendAddParam.setAddFriendItem(lists);
        String jsonString = JSON.toJSONString(friendAddParam);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.friend_add), jsonString));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")) {
            JSONArray jsonArray = jObject.getJSONArray("ResultItem");
            JSONObject jsonObject0 = jsonArray.getJSONObject(0);
            String result = jsonObject0.getString("ResultCode");
            if (result.equals("30539")) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 删除好友
     *
     * @param
     * @return
     */
    public Boolean friendDelete(Long userId, Long relevance) {
        Boolean flag = false;
        Map<Object, Object> friendDeleteMember = new HashMap<>();
        friendDeleteMember.put("From_Account", String.valueOf(userId));
        String source[] = {String.valueOf(relevance)};
        friendDeleteMember.put("To_Account", source);
        friendDeleteMember.put("DeleteType", "Delete_Type_Both");
        String jsonString = JSON.toJSONString(friendDeleteMember);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.friend_delete), jsonString));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")) {
            JSONArray jsonArray = jObject.getJSONArray("ResultItem");
            JSONObject jsonObject0 = jsonArray.getJSONObject(0);
            String result = jsonObject0.getString("ResultCode");
            if (result.equals("0")) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 添加黑名单
     *
     * @param
     * @return
     */
    public Boolean blackListAdd(Long userId, Long friendId) {
        Boolean flag = false;
        Map<Object, Object> friendDeleteMember = new HashMap<>();
        friendDeleteMember.put("From_Account", userId.toString());
        String source[] = {friendId.toString()};
        friendDeleteMember.put("To_Account", source);
        String jsonString = JSON.toJSONString(friendDeleteMember);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.black_list_add), jsonString));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")) {
            JSONArray jsonArray = jObject.getJSONArray("ResultItem");
            JSONObject jsonObject0 = jsonArray.getJSONObject(0);
            String result = jsonObject0.getString("ResultCode");
            if (result.equals("0")) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 移出黑名单
     *
     * @param
     * @return
     */
    public Boolean blackListDelete(Long userId, Long friendId) {
        Boolean flag = false;
        Map<Object, Object> friendDeleteMember = new HashMap<>();
        friendDeleteMember.put("From_Account", userId.toString());
        String source[] = {friendId.toString()};
        friendDeleteMember.put("To_Account", source);
        String jsonString = JSON.toJSONString(friendDeleteMember);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.black_list_delete), jsonString));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")) {
            JSONArray jsonArray = jObject.getJSONArray("ResultItem");
            JSONObject jsonObject0 = jsonArray.getJSONObject(0);
            String result = jsonObject0.getString("ResultCode");
            if (result.equals("0")) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 创建群聊
     *
     * @param groupChat
     * @return
     */
    public Boolean creategroup(GroupChat groupChat) {
        Boolean flag = false;
        User user = userDao.unique(groupChat.getCreateBy());
        CreateGroupParam param = new CreateGroupParam();
        param.setFaceUrl(groupChat.getHead());
        param.setOwner_Account(groupChat.getCreateBy());
        param.setType("Public");
        param.setGroupId(groupChat.getId().toString());
        if (groupChat.getName()==null){
            param.setName(user.getName()+"创建的群聊");
        }else {
            param.setName(groupChat.getName());
        }
        param.setApplyJoinOption("NeedPermission");
        String createGroupJson = JSON.toJSONString(param);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.create_group), createGroupJson));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")) {
            flag = true;
        }
        return flag;
    }

    /**
     * 增加群成员
     * @return
     */
    public List<CreateGroupReturn> addGroupMember(Long groupId,String ids, Integer silence) {
        Boolean flag = false;
        ArrayList memberList = new ArrayList<>();
        String[] splitids = ids.split(",");
        Long[] idArr = (Long[]) ConvertUtils.convert(splitids,Long.class);
        for (Long aLong : idArr) {
            Map<String, String> member = new HashMap<>();
            member.put("Member_Account",String.valueOf(aLong));
            memberList.add(member);
        }
        Map<Object, Object> addGroupMember = new HashMap<>();
        addGroupMember.put("GroupId",String.valueOf(groupId));
        addGroupMember.put("MemberList",memberList);
        if(silence != null){
            addGroupMember.put("Silence", silence);
        }
        String addGroupMemberJson = JSON.toJSONString(addGroupMember);//拼装json数据
        JSONObject addGroupMemberJObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.add_group_member), addGroupMemberJson));
        String actionStatusMember = addGroupMemberJObject.getString("ActionStatus");
        if (actionStatusMember.equals("OK")){
            JSONArray jsonArray = addGroupMemberJObject.getJSONArray("MemberList");
            List<CreateGroupReturn> returns = jsonArray.toJavaList(CreateGroupReturn.class);
            return returns;
        }
        return null;
    }

    /**
     * 删除群成员
     * @return
     */
    public Boolean deleteGroupMember(Long groupId,String ids) {
        String[] idArr = ids.split(",");
        Boolean flag = false;
        Map<Object, Object> deleteGroupMember = new HashMap<>();
        deleteGroupMember.put("GroupId",String.valueOf(groupId));
        deleteGroupMember.put("Silence","0");
        deleteGroupMember.put("MemberToDel_Account",idArr);
        String deleteGroupMemberJson = JSON.toJSONString(deleteGroupMember);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.delete_group_member), deleteGroupMemberJson));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")) {
            flag = true;
        }
        return flag;
    }

    /**
     * 查询用户在群组中的身份
     * @return
     */
    public String getRoleInGroup(Long groupId,Long userId) {
        Map<Object, Object> deleteGroupMember = new HashMap<>();
        deleteGroupMember.put("GroupId",String.valueOf(groupId));
        JSONArray array = new JSONArray();
        array.add(userId.toString());
        deleteGroupMember.put("User_Account",array);
        String deleteGroupMemberJson = JSON.toJSONString(deleteGroupMember);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.get_role_in_group), deleteGroupMemberJson));
        System.out.println("查询用户在群组中的身份 :" + jObject.toJSONString());
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")) {
            JSONArray userIdList = jObject.getJSONArray("UserIdList");
            if(userIdList != null){
                for (int i = 0; i < userIdList.size(); i++) {
                    JSONObject object = userIdList.getJSONObject(i);
                    if(userId.toString().equals(object.getString("Member_Account"))){
                        return object.getString("Role"); // // 成员角色：Owner/Admin/Member/NotMember
                    }
                }
            }
        }
        return null;
    }


    /**
     * 修改群成员昵称
     * @param groupMembers
     * @return
     */
    public  Boolean modifyGroupMemberInfo(GroupMembers groupMembers) {
        Boolean flag=false;
        Map<String, String> fmap = new HashMap<String, String>();
        fmap.put("GroupId",groupMembers.getGroupChatId().toString());
        fmap.put("Member_Account",groupMembers.getUserId().toString());
        fmap.put("NameCard", groupMembers.getNickName());
        String createGroupJson = JSON.toJSONString(fmap);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.modify_group_member_info), createGroupJson));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")){
            flag=true;
        }
        return flag;
    }

    /**
     * 设置群管理员 1设置 0取消
     * @return
     */
    public  Boolean setGroupMember(Long userId,Long groupId,Integer type) {
        Boolean flag=false;
        Map<String, String> fmap = new HashMap<String, String>();
        fmap.put("GroupId",String.valueOf(groupId));
        fmap.put("Member_Account",String.valueOf(userId));
        if (type.equals(1))
            fmap.put("Role", "Admin");
        if (type.equals(0))
            fmap.put("Role", "Member");
        String jsonString = JSON.toJSONString(fmap);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.modify_group_member_info), jsonString));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")){
            flag=true;
        }
        return flag;
    }

    /**
     * 修改加群方式
     * @param
     * @return
     */
    public  Boolean updateAddGroupWay(Long groupId,Integer type) {
        Boolean flag=false;
        Map<String, String> fmap = new HashMap<String, String>();
        fmap.put("GroupId",String.valueOf(groupId));
        if (type.equals(0)){
            fmap.put("ApplyJoinOption","DisableApply");
        }else if (type.equals(1)){
            fmap.put("ApplyJoinOption","NeedPermission");
        }else if (type.equals(2)){
            fmap.put("ApplyJoinOption","FreeAccess");
        }
        String jsonString = JSON.toJSONString(fmap);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.update_group_way), jsonString));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")){
            flag=true;
        }
        return flag;
    }

    /**
     * 修改群资料
     * @param
     * @return
     */
    public  Boolean updateGroupName(Long groupId,String name,String image) {
        Boolean flag=false;
        Map<String, String> fmap = new HashMap<String, String>();
        fmap.put("GroupId",String.valueOf(groupId));
        if (name!=null && !name.equals("")){
            fmap.put("Name",name);//群名称
        }
        if (image!=null && !image.equals("")){
            fmap.put("FaceUrl",image);//群头像
        }

        String jsonString = JSON.toJSONString(fmap);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.update_group_way), jsonString));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")){
            flag=true;
        }
        return flag;
    }

    /**
     * 转让群主
     * @param
     * @return
     */
    public  Boolean changeGroupOwner(Long groupId, Long memberId) {
        Boolean flag=false;
        Map<String, String> fmap = new HashMap<String, String>();
        fmap.put("GroupId",String.valueOf(groupId));
        fmap.put("NewOwner_Account",String.valueOf(memberId));
        String changeGroupOwnerJson = JSON.toJSONString(fmap);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.change_group_owner), changeGroupOwnerJson));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")){
            flag=true;
        }
        return flag;
    }

    /**
     * 解散群
     * @param
     * @return
     */
    public  Boolean destroyGroup(Long groupId) {
        Boolean flag=false;
        Map<String, String> fmap = new HashMap<String, String>();
        fmap.put("GroupId",String.valueOf(groupId));
        String destroyGroupJson = JSON.toJSONString(fmap);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.destroy_group), destroyGroupJson));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")){
            flag=true;
        }
        return flag;
    }

    /**
     * 查看是否在线
     * @param
     * @return
     */
    public  List<OpenimQuerystateReturn> openimQuerystate(Long userId) {
        Boolean flag=false;
        Map<String, Object> fmap = new HashMap<>();
        String[] split = userId.toString().split(",");
        fmap.put("To_Account",split);
        String destroyGroupJson = JSON.toJSONString(fmap);//拼装json数据
        JSONObject jObject = JSON.parseObject(this.executePost(this.getUrl(TencentCloudData.openim_querystate), destroyGroupJson));
        //返回值需解析Json串
        String actionStatus = jObject.getString("ActionStatus");
        String errorCode = jObject.getString("ErrorCode");
        if (errorCode.equals("0") && actionStatus.equals("OK")){
            JSONArray jsonArray = jObject.getJSONArray("QueryResult");
            List<OpenimQuerystateReturn> returns = jsonArray.toJavaList(OpenimQuerystateReturn.class);
            return returns;
        }else {
            return null;
        }
    }
}
